#!/bin/sh

# $1 level
# $2 path

REPODIR='/backup/tar-backups/'
DATEFILE="$REPODIR/tardate"
DO_FULL_BACKUP="no"
case "$1" in 
    --full-backup)
      DO_FULL_BACKUP="yes"
      ;;
esac

get_latest_backup (){
   # $1 - level
   # $2 - path
   LATESTDATE=""
   LVL=0
   while [ ! "$LATESTDATE" -a $LVL -lt $1 ];do
       LATESTDATE=`grep "$2 *$LVL" $DATEFILE|cut -d" " -f3-`
       if [ ! "$LATESTDATE" ];then
          LVL=`expr $LVL + 1`
       fi
   done
   if [ ! "$LATESTDATE" ];then
        LATESTDATE="null"
   fi
   echo "$LVL $LATESTDATE"
}

clean_tardate_file() {
   # $1 - level
   # $2 - path
   TMPDIR=`mktemp -d tardate.XXXXX`
   cp $DATEFILE $TMPDIR/tardate.tmp
   # this loop will remove all entries which have higher level than the just created backup
   LVL=$1
   while [ $LVL -le 9 ];do
      grep -v "$2 *$LVL" $TMPDIR/tardate.tmp > $TMPDIR/tardate.tmp1 # for linux compatibility
      mv $TMPDIR/tardate.tmp1 $TMPDIR/tardate.tmp
      LVL=`expr $LVL + 1`
   done
   cp $TMPDIR/tardate.tmp $DATEFILE
   rm -rf $TMPDIR
}

tar_up () {
   # $1   - level
   # $2   - path
   # $3   - tarballname
   # $4-  - extra tar arguments
   DATE=`get_latest_backup $1 $2|cut -d" " -f2-`
   EXTRA_ARGS=`echo $@|tr -s [:space:]|cut -d" " -f4-`
   TAR_ARGS="-cjPf $REPODIR/$3.$1.tar.bz2"
   if [ "$DATE" -a "$DATE" != "null" ];then
      tar $TAR_ARGS $EXTRA_ARGS --newer="$DATE" $2
   else
      tar $TAR_ARGS $EXTRA_ARGS $2
   fi
   RETVAL=$?
   clean_tardate_file $1 $2
   echo "$2 $1 `date "+%F %T"`" >> $REPODIR/tardate
   return $RETVAL
}


run_full_backup(){
   # $1 - path
   # $2 - tarball
   if [ ! -d $REPODIR/undo ];then
       mkdir -p $REPODIR/undo
   fi
   mv $REPODIR/$2.*.tar.bz2 $REPODIR/undo
   tar_up 0 $@
   if [ "$RETVAL" = "0" ];then
      rm -rf $REPODIR/undo
   fi
   return $RETVAL
}

run_backup (){
   # $1 = disk
   # $2 = image
   if [ ! -d $REPODIR ];then
       mkdir -p $REPODIR
   fi

   if [ "$DO_FULL_BACKUP" = "yes" ];then
      run_full_backup $@
   else
      TODAY=`date "+%A"`
      case "$TODAY" in
          Monday)
             run_full_backup $@
             ;;
          Tuesday)
             tar_up 1 $@
             ;;
          Wednesday)
             tar_up 2 $@
             ;;
          Thursday)
             tar_up 3 $@
             ;;
          Friday)
             tar_up 4 $@
             ;;
          Saturday)
             tar_up 5 $@
             ;;
          Sunday)
             tar_up 6 $@
             ;;
       esac
    fi
    if [ "$?" = "0" ];then
       echo "SUCCESS : $1"
    else
       echo "FAILURE : $1"
    fi
}

# run_backup <path-to-backup> <tarball-name> <extra-tar-options[optional]>
# run_backup /var/zope var.zope --exclude=Data.fs\* --exclude=\*.fsz --exclude=\*.dat
